package club.wx3609.images.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import club.wx3609.images.entity.Message;
import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Component;

@ServerEndpoint("/websocket/{Sender}")
@Component
public class WebSocketServer {

    private static MessageService messageService;
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static Integer onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //定义接受人
    private String Sender="";

    @Resource
    public void setMessageService(MessageService messageService){
        this.messageService=messageService;
    }

    /**
     * 连接建立成功调用的方法
     * */
    @OnOpen
    public void onOpen(Session session,@PathParam("Sender") String Sender){
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println(Sender+"进入聊天室,当前在线人数为" + getOnlineCount());
        this.Sender=Sender;
        try {
            sendMessage(Sender+"连接成功");
        } catch (IOException e) {
            System.out.println("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session,@PathParam("Sender") String Sender) {
        JSONArray jsonArray=JSONArray.parseArray(message);
        String Receiver=(String)jsonArray.get(0);
        String getMessage=(String)jsonArray.get(1);
        System.out.println("收到来自"+Sender+"的信息:"+getMessage);
        for (WebSocketServer item : webSocketSet) {
            try {
                /**
                 * 发送并保存消息
                 */
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                String nowTime=dateFormat.format(new Date());
                if(Receiver!=null) {
                    if (item.Sender.equals(Receiver)) {
                        item.sendMessage("<div class='dataMessage'>\n" +
                                "        <div>\n" +
                                "            <span class='userNumber'>"+Sender+"</span>&nbsp;<span class='nowTime fm'>"+nowTime+"</span>\n" +
                                "        </div>\n" +
                                "        <div>\n" +
                                "            "+ getMessage+"\n" +
                                "        </div>\n" +
                                "    </div>");

                    } else if (item.Sender.equals(Sender)) {
                        item.sendMessage("<div class='dataMessage right'>\n" +
                                "        <div>\n" +
                                "            <span class='userNumber'>"+Sender+"</span>&nbsp;<span class='nowTime fm'>"+nowTime+"</span>\n" +
                                "        </div>\n" +
                                "        <div>\n" +
                                "            "+ getMessage+"\n" +
                                "        </div>\n" +
                                "    </div>");
                        Message msg=new Message();
                        msg.setSender(Sender);
                        msg.setReceiver(Receiver);
                        msg.setMessageDate(nowTime);
                        msg.setMessageContent(getMessage);
                        messageService.addMessage(msg);
                    }
                }else{
                    item.sendMessage("<div class='dataMessage'>\n" +
                            "        <div>\n" +
                            "            <span class='userNumber'>"+Sender+"</span>&nbsp;<span class='nowTime fm'>"+nowTime+"</span>\n" +
                            "        </div>\n" +
                            "        <div>\n" +
                            "            "+ getMessage+"\n" +
                            "        </div>\n" +
                            "    </div>");
                    Message msg=new Message();
                    msg.setSender(Sender);
                    msg.setReceiver("全体成员");
                    msg.setMessageDate(nowTime);
                    msg.setMessageContent(getMessage);
                    messageService.addMessage(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}